package com.landi.carkey.util;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.landi.carkey.R;
import com.landi.carkey.interfaces.IDialogCheckPassWord;
import com.landi.carkey.interfaces.IDialogItemClickListener;
import com.landi.carkey.interfaces.IDialogTimeoutListener;
import com.landi.carkey.updata.VersionModel;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DialogFactory {
	private static Logger logger = Logger.getLogger(DialogFactory.class);
	private static HashMap<String, Dialog> dialogs = new HashMap<String, Dialog>();

	private static TextView tvTitle;
	private static TextView tvCount;
	private static LinearLayout llBtn;
	private static TextView tvMsg;
	private static TextView tvOk;
	private static TextView tvCancel;
	private static EditText etInput;
	private static CountDownTimer loadingTimer = null;

	public static boolean dismissAlert(Activity activity) {
		if (null != loadingTimer) {
			loadingTimer.cancel();
			loadingTimer = null;
		}
		Dialog dialog = (Dialog) dialogs.get(activity.toString());
		if ((dialog != null) && (dialog.isShowing()) && (!activity.isFinishing())) {
			try {
				dialog.dismiss();
			} catch (Exception e) {
				logger.error("弹框关闭异常：", e);
			}
			dialogs.remove(activity.toString());
			return true;
		} else {
			return false;
		}
	}

	private static Dialog createDialog(Activity activity) {

		dismissAlert(activity);
		Dialog dialog = new Dialog(activity, R.style.dialog_basic);
		dialog.setContentView(R.layout.dialog_show_tip);

		dialogs.put(activity.toString(), dialog);

		tvTitle = (TextView) dialog.findViewById(R.id.dialog_tip_title);
		tvCount = (TextView) dialog.findViewById(R.id.dialog_tip_time);
		llBtn = (LinearLayout) dialog.findViewById(R.id.dialog_btn_ll);
		tvMsg = (TextView) dialog.findViewById(R.id.dialog_tip_content);
		tvOk = (TextView) dialog.findViewById(R.id.dialog_tip_confirm_btn);
		tvCancel = (TextView) dialog.findViewById(R.id.dialog_tip_cancel_btn);
		// 设置对话框点击空白处不可关闭，点击返回按钮不可关闭。
		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				} else {
					return false; // 默认返回 false
				}
			}
		});
		dialog.setCanceledOnTouchOutside(false);
		return dialog;
	}

	/**
	 * 显示提示对话框，无取消按钮，不可取消，只能通过调用该类的dismissAlert方法
	 *
	 * @param context
	 * @param title
	 *            标题
	 * @param msg
	 *            内容
	 */
	public static void showMessage(Activity context, String title, String msg) {
		clearBeforeDialog(context);
		Dialog dialog = createDialog(context);
		llBtn.setVisibility(View.GONE);
		tvCount.setVisibility(View.GONE);
		tvTitle.setText(title);
		tvMsg.setText(msg);
		dialog.show();
	}

	/**
	 * 显示两个消息按钮的消息提示框，按钮点击事件均需实现,取消按钮可以传null；
	 *
	 * @param context
	 * @param title
	 * @param msg
	 * @param okTitle
	 * @param okClick
	 * @param canTitle
	 * @param canClick
	 */
	public static void showMessage(final Activity context, String title, String msg, String okTitle,
								   OnClickListener okClick, String canTitle, OnClickListener canClick) {
		clearBeforeDialog(context);
		Dialog dialog = createDialog(context);
		llBtn.setVisibility(View.VISIBLE);
		tvCount.setVisibility(View.GONE);
		tvTitle.setText(title);
		tvMsg.setText(msg);
		tvOk.setText(okTitle);
		tvCancel.setText(canTitle);
		tvOk.setOnClickListener(okClick);
		if (null != canClick) {
			tvCancel.setOnClickListener(canClick);
		} else {
			tvCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dismissAlert(context);
				}
			});
		}
		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME
						|| keyCode == KeyEvent.KEYCODE_MENU) {
					return true;
				}
				return false;
			}
		});
		dialog.show();
	}

	/**
	 * 显示加载对话框
	 *
	 * @param activity
	 * @param title
	 * @param msg
	 */
	public static void showLoadingDialog(final Activity activity, String title, String msg) {
		clearBeforeDialog(activity);
		ImageView ivLoad;
		TextView tvLoadTip;
		final TextView tvLoadCount;
		dismissAlert(activity);
		Dialog dialog = new Dialog(activity, R.style.dialog_loading_basic);
		dialog.setContentView(R.layout.dialog_loading);

		dialogs.put(activity.toString(), dialog);
		ivLoad = (ImageView) dialog.findViewById(R.id.loading_imgview);
		tvLoadTip = (TextView) dialog.findViewById(R.id.loading_tip_tv);
		tvLoadCount = (TextView) dialog.findViewById(R.id.loading_count_tv);
		// 启动动画
		Animation operatingAnim = AnimationUtils.loadAnimation(activity, R.anim.rotate);
		LinearInterpolator lin = new LinearInterpolator();
		operatingAnim.setInterpolator(lin);
		ivLoad.setAnimation(operatingAnim);
		// 设置对话框点击空白处不可关闭，点击返回按钮不可关闭。
		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				} else {
					return false; // 默认返回 false
				}
			}
		});
		dialog.setCanceledOnTouchOutside(false);

		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME
						|| keyCode == KeyEvent.KEYCODE_MENU) {
					return true;
				}
				return false;
			}
		});
		if(!TextUtils.isEmpty(msg)){
			tvLoadTip.setText(msg);
		}

		loadingTimer = new CountDownTimer(60000, 1000) {

			@Override
			public void onFinish() {
				// 计时完毕时触发
				logger.info("计时结束");
				dismissAlert(activity);
			}

			@Override
			public void onTick(long millisUntilFinished) {
				// 计时过程显示
				tvLoadCount.setText(String.valueOf(millisUntilFinished / 1000));
			}
		};
		loadingTimer.cancel();
		loadingTimer.start();
		if (null != dialog && !dialog.isShowing() && !activity.isFinishing()){
			dialog.show();
		}
	}

	/**
	 * 显示确认对话框
	 *
	 * @param context
	 * @param title
	 * @param msg
	 * @param okStr
	 */
	public static void showConfirmMessage(final Activity context, String title, String msg, String okStr,
										  final OnClickListener okClick) {
		clearBeforeDialog(context);
		Dialog dialog = createDialog(context);
		dialog.setCancelable(false);
		llBtn.setVisibility(View.VISIBLE);
		tvCount.setVisibility(View.GONE);
		tvTitle.setText(title);
		tvMsg.setText(msg);
		tvOk.setText(okStr);
		tvCancel.setVisibility(View.GONE);
		tvOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dismissAlert(context);
				if (null != okClick) {
					okClick.onClick(v);
				}
			}
		});
		dialog.show();
	}

	/**
	 * 显示存在倒计时的确认对话框，倒计时结算自动点击
	 *
	 * @param context
	 * @param title
	 * @param msg
	 * @param okStr
	 * @param timeout
	 *            单位毫秒
	 */
	public static void showConfirmMessageTimeout(int timeout, final Activity context, String title, String msg,
												 String okStr, final OnClickListener okClick) {
		clearBeforeDialog(context);
		Dialog dialog = createDialog(context);
		llBtn.setVisibility(View.VISIBLE);
		tvCount.setText("" + timeout / 1000);
		loadingTimer = new CountDownTimer(timeout, 1000) {

			@Override
			public void onFinish() {
				// 计时完毕时触发
				logger.info("计时结束");
				tvCount.setText("0");
				dismissAlert(context);
				if (null != okClick) {
					okClick.onClick(tvOk);
				}
			}

			@Override
			public void onTick(long millisUntilFinished) {
				// 计时过程显示
				tvCount.setText(String.valueOf(millisUntilFinished / 1000));
			}
		};
		if (timeout > 1000) {
			tvCount.setVisibility(View.VISIBLE);
			loadingTimer.start();
		} else {
			tvCount.setVisibility(View.GONE);
		}
		tvTitle.setText(title);
		tvMsg.setText(msg);
		tvOk.setText(okStr);
		tvCancel.setVisibility(View.GONE);
		tvOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dismissAlert(context);
				if (null != okClick) {
					okClick.onClick(v);
					loadingTimer.cancel();
				}
			}
		});
		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_BACK
						|| keyCode == KeyEvent.KEYCODE_MENU) {
					return true;
				}
				return false;
			}
		});
		dialog.show();

	}

	/**
	 * 显示确认对话框
	 *
	 * @param context
	 * @param title
	 * @param msg
	 * @param okStr
	 */
	public static void showConfirmMessage(final Activity context, String title, CharSequence msg, String okStr) {
		clearBeforeDialog(context);
		Dialog dialog = createDialog(context);
		llBtn.setVisibility(View.VISIBLE);
		tvCount.setVisibility(View.GONE);
		tvTitle.setText(title);
		tvMsg.setText(msg);
		tvOk.setText(okStr);
		tvCancel.setVisibility(View.GONE);
		tvOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dismissAlert(context);
			}
		});
		dialog.show();
	}

	public static void showDiscountDialog(final Activity activity, String title, CharSequence msg, String okStr) {

		clearBeforeDialog(activity);
		Dialog dialog = new Dialog(activity, R.style.dialog_basic);
		dialog.setContentView(R.layout.dialog_show_discountdetail);

		dialogs.put(activity.toString(), dialog);

		TextView tvTitle = (TextView) dialog.findViewById(R.id.dialog_tip_title);
		TextView tvMsg = (TextView) dialog.findViewById(R.id.dialog_tip_content);
		TextView tvOk = (TextView) dialog.findViewById(R.id.dialog_tip_confirm_btn);
		dialog.setCanceledOnTouchOutside(false);
		tvTitle.setText(title);
		if (!TextUtils.isEmpty(okStr)) {
			tvOk.setText(okStr);
		}
		tvMsg.setText(msg);
		tvOk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dismissAlert(activity);
			}
		});
		dialog.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				return true;
			}
		});
		dialog.show();
	}

	/**
	 * 显示输入密码对话框
	 * @param activity
	 * @param title
	 * @param okStr
	 * @param okClick
	 */
	public static void showInputPassWordDialog(final Activity activity, String title, String okStr,
											   final IDialogCheckPassWord okClick, String cancelStr, final
											   OnClickListener cancelCllick){

		clearBeforeDialog(activity);
		Dialog dialog = new Dialog(activity, R.style.dialog_basic);
		dialog.setContentView(R.layout.dialog_input_password);

		dialogs.put(activity.toString(), dialog);

		TextView tvTitle = (TextView) dialog.findViewById(R.id.dialog_tip_title);
		final EditText etPassWord = (EditText) dialog.findViewById(R.id.dialog_tip_et);
		TextView tvOk = (TextView) dialog.findViewById(R.id.dialog_tip_confirm_btn);
		TextView tvCancel = (TextView) dialog.findViewById(R.id.dialog_tip_cancel_btn);

		tvTitle.setText(title);
		if (!TextUtils.isEmpty(okStr)) {
			tvOk.setText(okStr);
		}

		tvOk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				okClick.onDialogCheckStr(etPassWord.getText().toString());
			}
		});

		if (!TextUtils.isEmpty(cancelStr)) {
			tvCancel.setText(cancelStr);
		}

		if (null != cancelCllick) {
			tvCancel.setOnClickListener(cancelCllick);
		} else {
			tvCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dismissAlert(activity);
				}
			});
		}
		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME
						|| keyCode == KeyEvent.KEYCODE_MENU) {
					return true;
				}
				return false;
			}
		});
		dialog.show();

	}

	public static void showUpdataVersionDialog(final Activity activity, VersionModel model, OnClickListener listener){

		if(activity.isFinishing()){
			return;
		}

		clearBeforeDialog(activity);
		Dialog dialog = new Dialog(activity, R.style.dialog_basic);
		dialog.setContentView(R.layout.dialog_show_updata_version);

		dialogs.put(activity.toString(), dialog);
		TextView tvTip = (TextView) dialog.findViewById(R.id.dialog_version_tip);
		TextView tvMsg = (TextView) dialog.findViewById(R.id.dialog_version_content);
		tvTip.setText(activity.getString(R.string.update_app_msg,model.getVersionSize()));
		tvMsg.setText(model.getVersionMsg());

		TextView tvOk = (TextView) dialog.findViewById(R.id.dialog_version_confirm_btn);
		TextView tvCancel = (TextView) dialog.findViewById(R.id.dialog_version_cancel_btn);

		tvCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dismissAlert(activity);
			}
		});
		if (listener!=null){
			tvOk.setOnClickListener(listener);
		}

		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME
						|| keyCode == KeyEvent.KEYCODE_MENU) {
					return true;
				}
				return false;
			}
		});
		dialog.show();

	}

	public static void showChooseListDialog(final Activity activity, String title, String okStr,
											final OnClickListener okClick, final String[] datas, final IDialogItemClickListener itemClick) {

		clearBeforeDialog(activity);
		Dialog dialog = new Dialog(activity, R.style.dialog_basic);
		dialog.setContentView(R.layout.dialog_choose_list);

		dialogs.put(activity.toString(), dialog);

		TextView tvTitle = (TextView) dialog.findViewById(R.id.dialog_tip_title);
		TextView tvCount = (TextView) dialog.findViewById(R.id.dialog_tip_time);
		LinearLayout llBtn = (LinearLayout) dialog.findViewById(R.id.dialog_btn_ll);
		TextView tvMsg = (TextView) dialog.findViewById(R.id.dialog_tip_content);
		TextView tvOk = (TextView) dialog.findViewById(R.id.dialog_tip_confirm_btn);
		TextView tvCancel = (TextView) dialog.findViewById(R.id.dialog_tip_cancel_btn);
		ListView listView = (ListView) dialog.findViewById(R.id.dialog_choose_listview);
		// 设置对话框点击空白处不可关闭，点击返回按钮不可关闭。
		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				} else {
					return false; // 默认返回 false
				}
			}
		});
		dialog.setCanceledOnTouchOutside(false);
		tvTitle.setText(title);
		tvCancel.setVisibility(View.GONE);
		if (TextUtils.isEmpty(okStr)) {
			tvOk.setVisibility(View.GONE);
			llBtn.setVisibility(View.GONE);
		}
		tvOk.setText(okStr);
		tvOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != okClick) {
					okClick.onClick(v);
				} else {
					dismissAlert(activity);
				}
			}
		});
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		String COL_NAME = "colName";
		for (int i = 0; i < datas.length; i++) {
			Map<String, String> map = new HashMap<String, String>();
			map.put(COL_NAME, datas[i].trim());
			list.add(map);
		}
		SimpleAdapter adapter = new SimpleAdapter(activity, list, R.layout.item_simple_text, new String[] { COL_NAME },
				new int[] { R.id.simple_text_value });
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				itemClick.onDialogItemClick(view, datas[position], position);
			}
		});
		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		dialog.show();
	}

	private static Toast mToast;

	public static void showTip(Context mContext, String msg) {
		if (mToast == null) {
			mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
		}
		mToast.setText(msg);
		mToast.show();
	}

	/**
	 * 显示加载对话框
	 *
	 * @param timeout
	 *            超时后自动消失 单位毫秒
	 * @param activity
	 * @param tip
	 */
	public static void showLoadingTip(final int timeout, final Activity activity, String tip,
									  final IDialogTimeoutListener listener) {
		clearBeforeDialog(activity);
		ProgressDialog printDialog = null;
		printDialog = new ProgressDialog(activity);
		printDialog.setMessage(tip);
		printDialog.setCancelable(false);
		printDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				return true;
			}
		});
		dialogs.put(activity.toString(), printDialog);
		loadingTimer = new CountDownTimer(timeout, 1000) {

			@Override
			public void onFinish() {
				// 计时完毕时触发
				// if(dismissAlert(activity)){
				listener.onDialogTimeout("对话框超时");
				dismissAlert(activity);
				logger.debug("结束打印");
				// }
			}

			@Override
			public void onTick(long millisUntilFinished) {
				// 计时过程显示
				if (millisUntilFinished >= timeout) {
					logger.debug("打印框计时结束");
				}
			}
		};
		loadingTimer.start();
		if(!activity.isFinishing() && !printDialog.isShowing()){
			printDialog.show();
		}
	}

	/**
	 * 清除map里面同一个activity弹出的对话框
	 *
	 * @param activity
	 */
	public static void clearBeforeDialog(Activity activity) {
		Dialog dialog = (Dialog) dialogs.get(activity.toString());
		if (null != dialog && dialog.isShowing() && !activity.isFinishing()) {
			try {
				dialog.dismiss();
			} catch (Exception e) {
				logger.error("弹框关闭异常：", e);
			}
			dialogs.remove(activity.toString());
		} else {
			return;
		}
	}
}
